package com.jmyd.sharding.base.task;

import org.apache.commons.lang3.StringUtils;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author samphin
 * @date 2022/6/14 11:40
 */
public class CustomThreadFactory implements ThreadFactory {
    /**
     * 线程前缀,采用AtomicInteger实现线程编号线程安全自增
     */
    private final AtomicInteger atomicInteger = new AtomicInteger(1);
    /**
     * 线程命名前缀
     */
    private final String namePrefix;
    /**
     * 线程工厂创建的线程是否是守护线程
     */
    private final boolean isDaemon;

    public CustomThreadFactory(String prefix, boolean daemon) {
        if (StringUtils.isNoneBlank(prefix)) {
            this.namePrefix = prefix;
        } else {
            this.namePrefix = "thread_pool";
        }
        // 是否是守护线程
        isDaemon = daemon ;
    }

    @Override
    public Thread newThread(Runnable runnable) {
        Thread thread = new Thread(runnable, namePrefix + "-" + atomicInteger.getAndIncrement());
        thread.setDaemon(isDaemon);
        // 设置线程优先级
        if (thread.getPriority() != Thread.NORM_PRIORITY) {
            thread.setPriority(Thread.NORM_PRIORITY);
        }
        return thread;
    }
}
